package com.liber.sun.utils;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;


import java.io.*;

/**
 * Created by sunlingzhi on 2017/10/19.
 */
public class XmlUtils {

    public static Document parseFile(File xmlFile) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;

        builder=factory.newDocumentBuilder();
        Document doc = builder.parse(xmlFile);
        return doc;
    }

    public static String docToString(Document doc, String encoding) {

            StringWriter stringWriter = null;
            try {
                stringWriter = new StringWriter();
                if(doc != null){
                    OutputFormat format = new OutputFormat(doc,"UTF-8",true);
                    //format.setIndenting(true);//设置是否缩进，默认为true
                    //format.setIndent(4);//设置缩进字符数
                    //format.setPreserveSpace(false);//设置是否保持原来的格式,默认为 false
                    //format.setLineWidth(500);//设置行宽度
                    XMLSerializer serializer = new XMLSerializer(stringWriter,format);
                    serializer.asDOMSerializer();
                    serializer.serialize(doc);
                    return stringWriter.toString();
                } else {
                    return null;
                }
            } catch (Exception e) {
                return null;
            } finally {
                if(stringWriter != null){
                    try {
                        stringWriter.close();
                    } catch (IOException e) {
                        return null;
                    }
                }
            }
        }

    public static void  saveDocToXMLFile(String path, Document doc)throws IOException {
        try {
            Source source = new DOMSource(doc);
            Result result = new StreamResult(new File(path));
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
        } catch (Exception e) {
            return;
        }
    }
}
